/**
 * 
 */
package cn.ad.server.web.servlet.v2.parser;

import cn.ad.server.common.utils.IPUtils;
import cn.ad.server.web.servlet.v2.requests.ImpressionRequest;
import cn.ad.server.web.servlet.v2.requests.TrackingRequest;
import cn.ad.server.web.spring.model.IAdserverRequest;
import cn.ad.server.web.spring.model.IAdserverResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Wu Chengjun
 *
 */
public class DefaultImpressionRequestParser extends TrackingRequestParser {
	
	private static Logger LOGGER = LoggerFactory.getLogger(DefaultImpressionRequestParser.class);

	/**
	 * 
	 */
	public DefaultImpressionRequestParser() {
		
	}
	

	@Override
	public void writeResponse(IAdserverResponse adResponse, HttpServletResponse response)
			throws AdRequestParseException {
		super.writeResponse(adResponse, response);
		
	}

	@Override
	public void writeResponse(IAdserverRequest adRequest, IAdserverResponse adResponse, HttpServletRequest request,
			HttpServletResponse response) throws AdRequestParseException {
		response.setContentType("image/jpg");
		try (InputStream is = DefaultImpressionRequestParser.class.getResourceAsStream("/1x1.png");
             ServletOutputStream os = response.getOutputStream()) {
			byte[] b = new byte[1024];
			int len = 0;
			while ((len = is.read(b)) != -1) {
				os.write(b, 0, len);
			}
			os.flush();
		}catch(IOException e) {
			LOGGER.warn("写入响应出现IO异常, 请求IP, {}, 请求URL{}, 异常原因{} ", IPUtils.parseIp(request), request.getRequestURL(), e.getMessage());
		}
	}


	/* (non-Javadoc)
	 * @see cn.falconnect.adserver.adapter.TrackingRequestParser#createTrackingRequest(javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public TrackingRequest createTrackingRequest(HttpServletRequest request) throws AdRequestParseException {
		return new ImpressionRequest();
	}
}
